const { defineConfig } = require('@vue/cli-service');
const { resolve } = require('path');
const path = require('path');
const WebpackBar = require('webpackbar');
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i; // 开启gzip压缩， 按需写入
const {
    publicPath,
    assetsDir,
    outputDir,
    lintOnSave,
    transpileDependencies,
    title,
    devPort,
    isProd
} = require('./src/config/vueDefaultConfig');
module.exports = defineConfig({
    publicPath,
    assetsDir,
    outputDir,
    lintOnSave,
    transpileDependencies,
    devServer: {
        host: 'localhost',
        hot: true,
        port: devPort,
        open: true
    },
    pluginOptions: {
        'style-resources-loader': {
            preProcessor: 'scss',
            patterns: [
                path.resolve(__dirname, 'src/styles/variables.module.scss'),
                path.resolve(__dirname, 'src/styles/mixins.scss')
            ]
        }
    },
    chainWebpack(config) {
        config.resolve.symlinks(true); // 修复热更新失效
        config.plugin('html').tap((args) => {
            // 修复 Lazy loading routes Error
            args[0].chunksSortMode = 'none';
            args[0].title = title;
            return args;
        });
        // 配置svg规则排除icons目录中svg文件处理
        config.module.rule('svg').exclude.add(resolve('src/icons')).end();
        // 新增icons规则，设置svg-sprite-loader处理icons目录中的svg
        config.module
            .rule('icons')
            .test(/\.svg$/)
            .include.add(resolve('src/icons'))
            .end()
            .use('svg-sprite-loader')
            .loader('svg-sprite-loader')
            .options({ symbolId: 'icon-[name]' })
            .end();
    },
    configureWebpack() {
        const plugins = [];
        if (isProd) {
            plugins.push(
                new CompressionWebpackPlugin({
                    filename: '[path][base].gz',
                    algorithm: 'gzip',
                    test: productionGzipExtensions,
                    //大于10k的进行压缩
                    threshold: 10240,
                    //只有压缩率比这个值小的文件才会被处理，压缩率=压缩大小/原始大小，如果压缩后和原始文件大小没有太大区别，就不用压缩
                    minRatio: 0.8,
                    //是否删除原文件，最好不删除，服务器会自动优先返回同名的.gzip资源，如果找不到还可以拿原始文件
                    deleteOriginalAssets: false
                })
            );
        }
        return {
            resolve: {
                alias: {
                    '@': resolve('src')
                },
                extensions: ['.ts', '.vue', '.json', '.js', 'json'],
                fallback: { path: require.resolve('path-browserify') }
            },
            devtool: isProd ? false : 'eval-cheap-module-source-map',
            plugins: [
                new WebpackBar({
                    name: title
                }),
                ...plugins
            ]
        };
    }
});
